import mongoose from 'mongoose'
const { ErrorHandler } = require('./common/errorHandler')
const ShopProducts = mongoose.model('ShopProducts')
mongoose.set('useFindAndModify', false)
const { LocalRequestAllowed } = require('./common/localRequestAllowed')
const { PageChecker } = require('./common/page')


export const getShopList = async (ctx) => {
  try {
    await LocalRequestAllowed(ctx).then(async () => { // 只允许本地请求
      const { pageNum, pageSize, type } = ctx.request.body
      await PageChecker(pageSize, pageNum) // 分页校验
      if(type){
        const conditon = { online: true, type } // 查询条件
        const total = await ShopProducts.find(conditon).count().exec();
        const data = await ShopProducts.find(conditon)
            .skip((Number(pageNum) - 1) * Number(pageSize))
            .limit(Number(pageSize))   
            .sort({'_id':-1})
            .exec()
        ctx.body = {
          success: true,
          data,
          total,
          pageNum,
          pageSize
        }
      } else {
        ctx.body = {
          success: false,
          data: 'type未传'
        }
      }
    })
  } catch (e) {
    ErrorHandler(e, ctx)
  }
}
